package sing.myapp.ui.h5

import android.annotation.SuppressLint
import android.os.Build
import android.webkit.WebSettings
import androidx.fragment.app.FragmentActivity
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.baidu.liantian.jni.Asc.ws
import com.github.lzyzsd.jsbridge.BridgeHandler
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.CallBackFunction
import sing.core.ext.util.loge
import sing.core.ext.util.showShort
import sing.core.ext.util.statusBarHeight
import sing.myapp.net.interceptor.MyParamsInterceptor
import sing.myapp.router.JumpCenter


/**
 * 新增 WebView 统一配置
 */
class WebviewUtils(private val mActivity: FragmentActivity, private val mWebView: BridgeWebView) {

    fun initWebViewSetting() {
        initWebViewSetting(mWebView)
    }

    @SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
    private fun initWebViewSetting(webView: BridgeWebView?) {
        if (webView == null) return

//        if (ConfigUtil.shouldClear()){
//            ConfigUtil.setShouldClear(false);
//            webView.clearCache(true);
//            webView.clearHistory();
//            webView.requestFocus();
//        }
        val settings = webView.settings
//        settings.userAgentString = "${settings.userAgentString}SoundStageApp"
        settings.pluginState = WebSettings.PluginState.ON
//        settings.setAppCacheEnabled(true)
        // 缓存白屏
        // /data/user/0/com.sound.stage/cache/webcache
        val appCachePath = mActivity.cacheDir.absolutePath + "/webcache"
        // 设置 Application Caches 缓存目录
//        settings.setAppCachePath(appCachePath)
        settings.databasePath = appCachePath
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        settings.databaseEnabled = true
        settings.useWideViewPort = true
        settings.textZoom = 100
        //不显示webview缩放按钮
        settings.displayZoomControls = false
        //混合网络协议内容
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        // 网页内容的宽度是否可大于WebView控件的宽度
        settings.loadWithOverviewMode = false
        // 保存表单数据
        settings.saveFormData = true
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        settings.setSupportZoom(true)
        settings.builtInZoomControls = true
        // 启动应用缓存
//        settings.setAppCacheEnabled(true)
        // 设置缓存模式
        /*settings.setCacheMode(WebSettings.LOAD_DEFAULT);*/
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        // 设置缓存模式
        /*settings.setCacheMode(WebSettings.LOAD_DEFAULT);*/
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
//        settings.setUseWideViewPort(true)
        // 缩放比例 1
        webView.setInitialScale(1)
        // 告诉WebView启用JavaScript执行。默认的是false。
        settings.javaScriptEnabled = true
        //  页面加载好以后，再放开图片 解决图片不显示
        settings.blockNetworkImage = false
        // 使用localStorage则必须打开
        settings.domStorageEnabled = true
        // 排版适应屏幕
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        // WebView是否支持多个窗口。
        settings.setSupportMultipleWindows(true)
        // 避免中文乱码
        settings.defaultTextEncodingName = "utf-8"
        // 自动加载图片
        settings.loadsImagesAutomatically = true
        settings.allowContentAccess = true
        settings.allowFileAccess = true

        settings.savePassword = true
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            settings.savePassword = false
        }

        // 获取Token
        webView.registerHandler("appGetToken", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appGetToken：$data".loge("H5 => ")
            val obj = JSONObject()
            val map = MyParamsInterceptor().getParams()
            for (key in map.keys) {
                obj[key] = map[key]
            }

            function?.onCallBack(obj.toString())
        })

        // StatusBar高度
        webView.registerHandler("appGetStatusBarHeight", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appGetStatusBarHeight：$data".loge("H5 => ")
            val obj = JSONObject()

            var a = mActivity.resources.displayMetrics.densityDpi / 160.0

            obj["height"] = mActivity.statusBarHeight  / a

            function?.onCallBack(obj.toString())
        })
        // StatusBar高度
        webView.registerHandler("appGetTitleHeight", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appGetTitleHeight：$data".loge("H5 => ")
            val obj = JSONObject()
            val a = mActivity.resources.displayMetrics.densityDpi / 160.0
            obj["height"] = mActivity.resources.getDimensionPixelSize(sing.uiadapter.R.dimen.dp_48_x) / a
            function?.onCallBack(obj.toString())
        })

        // 后退
        webView.registerHandler("appToRoute", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appToRoute：$data".loge("H5 => ")
            val obj = JSON.parseObject(data)
            if (obj.containsKey("pageName")){
                JumpCenter.toWebView("${obj["pageName"]}",showStatus = true,isBlackBack = true)
            }else{
                goBack?.goBack(0)
            }
        })

        webView.registerHandler("appToClose", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appToClose：$data".loge("H5 => ")
            goBack?.goBack(1)
        })

        // 弹窗
        webView.registerHandler("showMsg", BridgeHandler { data: String?, function: CallBackFunction? ->
            "showMsg：$data".loge("H5 => ")
            val obj = JSON.parseObject(data)
            if (obj.containsKey("msg")){
                "${obj["msg"]}".showShort()
            }
        })

        // 注销
        webView.registerHandler("appToCancel", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appToCancel：$data".loge("H5 => ")
            JumpCenter.toLogin()
        })

        // 打开一个新的web
        webView.registerHandler("appToActivityWeb", BridgeHandler { data: String?, function: CallBackFunction? ->
            "appToActivityWeb：$data".loge("H5 => ")
            val obj = JSON.parseObject(data)
            JumpCenter.toWebView("${obj["url"]}", showStatus = true, showTitle = true)
        })
    }

    var goBack: GoBack? = null
    interface GoBack {
        fun goBack(type: Int) // 0是后退，1是直接关闭
    }
}